<template>
  <div class="map-wrapper">
    <div ref="mapContainer" class="map-container"></div>
    <div ref="floodChart" class="flood-chart" v-show="showFloodChart"></div>
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'MapComponent',
  props: {
    selectedYear: {
      type: Number,
      default: 2024
    }
  },
  setup(props) {
    const mapContainer = ref(null)
    const floodChart = ref(null)
    const showFloodChart = ref(false)
    let mapChart = null
    
    // 各省洪汛数据（按年份和省份）
    const provinceFloodData = {}
    
    // 基础省份数据模板 - 使用ECharts地图标准名称
    const baseProvinces = [
      { name: '北京市', value: 45 },
      { name: '天津市', value: 38 },
      { name: '上海市', value: 52 },
      { name: '重庆市', value: 78 },
      { name: '河北省', value: 89 },
      { name: '河南省', value: 156 },
      { name: '云南省', value: 134 },
      { name: '辽宁省', value: 67 },
      { name: '黑龙江省', value: 98 },
      { name: '湖南省', value: 187 },
      { name: '安徽省', value: 145 },
      { name: '山东省', value: 123 },
      { name: '新疆维吾尔自治区', value: 23 },
      { name: '江苏省', value: 167 },
      { name: '浙江省', value: 134 },
      { name: '江西省', value: 178 },
      { name: '湖北省', value: 156 },
      { name: '广西壮族自治区', value: 145 },
      { name: '甘肃省', value: 34 },
      { name: '山西省', value: 67 },
      { name: '内蒙古自治区', value: 45 },
      { name: '陕西省', value: 78 },
      { name: '吉林省', value: 56 },
      { name: '福建省', value: 89 },
      { name: '贵州省', value: 123 },
      { name: '广东省', value: 167 },
      { name: '青海省', value: 12 },
      { name: '西藏自治区', value: 8 },
      { name: '四川省', value: 145 },
      { name: '宁夏回族自治区', value: 23 },
      { name: '海南省', value: 34 }
    ]
    
    // 为每个年份生成数据（2019-2025）
    for (let year = 2019; year <= 2025; year++) {
      const yearMultiplier = 0.8 + (year - 2019) * 0.1 // 年份递增因子
      provinceFloodData[year] = baseProvinces.map(province => {
        const value = Math.floor(province.value * yearMultiplier * (0.8 + Math.random() * 0.4))
        return {
          name: province.name,
          value: value
        }
      })
    }

    // 获取洪汛等级颜色
    const getFloodColor = (value) => {
      if (value < 30) return '#4c9bfd'   // 轻微 - 蓝色
      if (value < 60) return '#6acca3'   // 一般 - 绿色  
      if (value < 100) return '#eacf19'  // 较重 - 黄色
      if (value < 150) return '#ed8884'  // 严重 - 橙色
      return '#ed3f35'                   // 特重 - 红色
    }

    // 获取洪汛等级描述
    const getFloodLevelText = (value) => {
      if (value < 30) return '轻微'
      if (value < 60) return '一般'
      if (value < 100) return '较重'
      if (value < 150) return '严重'
      return '特重'
    }
    
    // 初始化中国地图
    const initChinaMap = async () => {
      if (!mapContainer.value) return
      
      mapChart = echarts.init(mapContainer.value)
      console.log('初始化地图，当前年份:', props.selectedYear)
      
      // 尝试加载真实中国地图
      try {
        const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
        const chinaGeoJson = await response.json()
        
        // 注册中国地图
        echarts.registerMap('china', chinaGeoJson)
        console.log('中国地图注册成功')
        
        // 初始化真实地图
        updateMapData()
        
      } catch (error) {
        console.warn('中国地图数据加载失败，使用简化版地图', error)
        // 使用简化版地图
        initSimpleMap()
      }
    }

    // 更新地图数据
    const updateMapData = () => {
      if (!mapChart) return
      
      const currentYearData = provinceFloodData[props.selectedYear] || []
      console.log('更新地图数据，年份:', props.selectedYear, '数据长度:', currentYearData.length)
      
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: `${props.selectedYear}年全国洪汛情况分布`,
          left: 'center',
          top: '2%',
          textStyle: {
            color: '#fff',
            fontSize: 16,
            fontWeight: 'bold',
            textShadowColor: 'rgba(0, 108, 255, 0.8)',
            textShadowBlur: 10
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            console.log('Tooltip params:', params)
            // 从数据源中查找对应的数据
            const data = currentYearData.find(item => params.name.indexOf(item.name) > -1)
            console.log("data",currentYearData);
            if (data) {
              const level = getFloodLevelText(data.value)
              const color = getFloodColor(data.value)
              return `
                <div style="background: linear-gradient(135deg, rgba(0,0,0,0.95) 0%, rgba(0,20,40,0.95) 100%); 
                            border: 1px solid #006cff; border-radius: 8px; padding: 12px; 
                            box-shadow: 0 8px 32px rgba(0,0,0,0.8);">
                  <div style="color: #fff; font-weight: bold; margin-bottom: 8px; font-size: 16px; 
                             text-shadow: 0 0 10px rgba(0,242,241,0.8);">${params.name}</div>
                  <div style="color: #4c9bfd; margin-bottom: 6px; display: flex; justify-content: space-between;">
                    <span>受灾程度:</span> 
                    <span style="color: ${color}; font-weight: bold; 
                                text-shadow: 0 0 8px ${color};">${level}</span>
                  </div>
                  <div style="color: #4c9bfd; margin-bottom: 6px; display: flex; justify-content: space-between;">
                    <span>受灾人数:</span> 
                    <span style="color: #00f2f1; font-weight: bold; font-family: 'Consolas', monospace;
                                text-shadow: 0 0 8px rgba(0,242,241,0.6);">${data.value}人</span>
                  </div>
                  <div style="color: #6acca3; font-size: 12px; margin-top: 8px; text-align: center;
                             border-top: 1px solid rgba(106,204,163,0.3); padding-top: 6px;">
                    🖱️ 点击查看详细信息
                  </div>
                </div>
              `
            }
            return `<div style="color: #fff; padding: 8px;">${params.name}<br/>暂无数据</div>`
          },
          backgroundColor: 'transparent',
          borderWidth: 0
        },
        visualMap: {
          min: 0,
          max: 200,
          left: '2%',
          bottom: '5%',
          text: ['严重', '轻微'],
          textStyle: {
            color: '#fff',
            fontSize: 12
          },
          inRange: {
            // 深色背景搭配的渐变色：蓝绿为主，严重时转红
            color: ['#003a8c', '#006cff', '#00f2f1', '#9fe6b8', '#ed3f35']
          },
          calculable: true,
          orient: 'horizontal',
          itemWidth: 20,
          itemHeight: 140,
          backgroundColor: 'rgba(0, 0, 0, 0.3)',
          borderColor: '#006cff',
          borderWidth: 1,
          borderRadius: 6
        },
        series: [
          {
            name: '洪汛情况',
            type: 'map',
            map: 'china',
            roam: true,
            scaleLimit: {
              min: 0.8,
              max: 3
            },
            zoom: 1.5,
            center: [104.114129, 37.550339],
            data: currentYearData,
            itemStyle: {
              borderColor: 'rgba(0, 108, 255, 0.8)',
              borderWidth: 1.5,
              shadowColor: 'rgba(0, 108, 255, 0.4)',
              shadowBlur: 15
            },
            emphasis: {
              itemStyle: {
                areaColor: 'rgba(0, 242, 241, 0.6)',
                borderColor: '#00f2f1',
                borderWidth: 3,
                shadowColor: 'rgba(0, 242, 241, 0.8)',
                shadowBlur: 25
              },
              label: {
                show: true,
                color: '#fff',
                fontSize: 14,
                fontWeight: 'bold',
                textShadowColor: 'rgba(0, 0, 0, 0.8)',
                textShadowBlur: 4
              }
            }
          }
        ]
      }
      
      mapChart.setOption(option, true)
      
      // 添加点击事件
      mapChart.on('click', (params) => {
        console.log('地图点击事件:', params)
        const data = currentYearData.find(item => params.name.indexOf(item.name) > -1)
        if (data) {
          showProvinceDetail(params.name, data)
        }
      })
    }
    
    // 简化版地图（当无法加载完整地图数据时使用）
    const initSimpleMap = () => {
      const currentYearData = provinceFloodData[props.selectedYear] || []
      console.log('=== 调试信息 ===')
      console.log('当前年份:', props.selectedYear)
      console.log('数据长度:', currentYearData.length)
      console.log('前3个数据:', currentYearData.slice(0, 3))
      
      if (currentYearData.length === 0) {
        console.error('没有找到数据！')
        return
      }
      
      // 创建一个简单的测试图表
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: `${props.selectedYear}年全国洪汛情况 (共${currentYearData.length}个省区)`,
          left: 'center',
          top: '5%',
          textStyle: {
            color: '#fff',
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return `${params.name}<br/>: ${params.value}万人<br/>等级: ${getFloodLevelText(params.value)}`
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          top: '15%',
          bottom: '10%'
        },
        xAxis: {
          type: 'category',
          data: currentYearData.map(item => item.name),
          axisLabel: {
            color: '#4c9bfd',
            fontSize: 9,
            rotate: 45
          },
          axisLine: {
            lineStyle: {
              color: '#006cff'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '受灾人数(人)',
          nameTextStyle: {
            color: '#4c9bfd'
          },
          axisLabel: {
            color: '#4c9bfd'
          },
          axisLine: {
            lineStyle: {
              color: '#006cff'
            }
          }
        },
        series: [
          {
            name: '洪汛情况',
            type: 'bar',
            data: currentYearData.map(item => ({
              name: item.name,
              value: item.value,
              itemStyle: {
                color: getFloodColor(item.value)
              }
            })),
            barWidth: '60%'
          }
        ]
      }
      
      console.log('设置图表配置:', option)
      mapChart.setOption(option, true)
      
      // 添加点击事件
      mapChart.on('click', (params) => {
        console.log('点击事件:', params)
        const data = currentYearData.find(item => item.name === params.name)
        if (data) {
          showProvinceDetail(params.name, data)
        }
      })
    }
    
    // 显示省份详细信息
    const showProvinceDetail = (provinceName, data) => {
      if (!data) return
      
      showFloodChart.value = true
      
      nextTick(() => {
        if (!floodChart.value) return
        
        const detailChart = echarts.init(floodChart.value)
        
        // 模拟该省份的详细数据
        const detailData = {
          rainfall: Math.floor(data.value * 2.5 + Math.random() * 50),
          affected: data.value,
          rescued: Math.floor(data.value * 0.85 + Math.random() * 10),
          damage: Math.floor(data.value * 1.8 + Math.random() * 30)
        }
        
        const option = {
          backgroundColor: 'rgba(0, 0, 0, 0.9)',
          title: {
            text: `${provinceName} - ${props.selectedYear}年洪汛详情`,
            left: 'center',
            top: '5%',
            textStyle: {
              color: '#fff',
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#006cff',
            borderWidth: 1,
            textStyle: {
              color: '#fff'
            }
          },
          legend: {
            data: ['降雨量(mm)', '受灾人数(人)', '救援人数(人)', '经济损失(亿)'],
            top: '15%',
            textStyle: {
              color: '#4c9bfd',
              fontSize: 10
            }
          },
          grid: {
            left: '10%',
            right: '10%',
            top: '35%',
            bottom: '15%'
          },
          xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月'],
            axisLabel: {
              color: '#4c9bfd',
              fontSize: 10
            },
            axisLine: {
              lineStyle: {
                color: '#006cff'
              }
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              color: '#4c9bfd',
              fontSize: 10
            },
            axisLine: {
              lineStyle: {
                color: '#006cff'
              }
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 108, 255, 0.2)'
              }
            }
          },
          series: [
            {
              name: '降雨量(mm)',
              type: 'line',
              data: [
                detailData.rainfall * 0.3,
                detailData.rainfall * 0.5,
                detailData.rainfall * 0.8,
                detailData.rainfall,
                detailData.rainfall * 0.7,
                detailData.rainfall * 0.4
              ],
              smooth: true,
              lineStyle: {
                color: '#00f2f1',
                width: 2
              },
              itemStyle: {
                color: '#00f2f1'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(0, 242, 241, 0.3)' },
                  { offset: 1, color: 'rgba(0, 242, 241, 0.1)' }
                ])
              }
            },
            {
              name: '受灾人数(人)',
              type: 'bar',
              data: [
                detailData.affected * 0.2,
                detailData.affected * 0.4,
                detailData.affected * 0.7,
                detailData.affected,
                detailData.affected * 0.8,
                detailData.affected * 0.3
              ],
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#ed8884' },
                  { offset: 1, color: '#ed3f35' }
                ])
              }
            }
          ]
        }
        
        detailChart.setOption(option)
      })
    }

    // 验证数据完整性
    const validateData = () => {
      console.log('=== 数据验证 ===')
      for (let year = 2019; year <= 2025; year++) {
        const data = provinceFloodData[year]
        console.log(`${year}年数据:`, data ? `${data.length}个省区` : '无数据')
        if (data && data.length > 0) {
          console.log(`${year}年前3个:`, data.slice(0, 3))
        }
      }
    }

    // 监听年份变化
    watch(() => props.selectedYear, (newYear) => {
      console.log('年份变化:', newYear)
      console.log('新年份数据:', provinceFloodData[newYear])
      console.log('数据长度:', provinceFloodData[newYear] ? provinceFloodData[newYear].length : 0)
      
      if (mapChart) {
        // 检查是否已注册中国地图
        if (echarts.getMap('china')) {
          console.log('更新真实地图数据')
          updateMapData()
        } else {
          console.log('使用简化版地图')
          initSimpleMap()
        }
      }
      showFloodChart.value = false
    })

    onMounted(async () => {
      // 验证数据
      validateData()
      
      // 确保DOM已经渲染完成
      await nextTick()
      // 延迟一点时间确保容器完全准备好
      setTimeout(() => {
        initChinaMap()
      }, 100)
    })

    return {
      mapContainer,
      floodChart,
      showFloodChart
    }
  }
}
</script>

<style scoped>
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: 8px;
}

.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 20%, rgba(0, 108, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(106, 204, 163, 0.1) 0%, transparent 50%);
  pointer-events: none;
  z-index: 1;
}

.flood-chart {
  position: absolute;
  top: 15%;
  right: 2%;
  width: 320px;
  height: 220px;
  background: 
    linear-gradient(135deg, rgba(0, 0, 0, 0.95) 0%, rgba(0, 20, 40, 0.95) 100%);
  border: 1px solid #006cff;
  border-radius: 12px;
  z-index: 1000;
  backdrop-filter: blur(15px);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.8),
    inset 0 1px 0 rgba(255, 255, 255, 0.1),
    0 0 0 1px rgba(0, 108, 255, 0.3);
  overflow: hidden;
}

.flood-chart::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, 
    transparent 0%, 
    rgba(0, 108, 255, 0.1) 50%, 
    transparent 100%);
  animation: chartScan 3s linear infinite;
}

@keyframes chartScan {
  0% { left: -100%; }
  100% { left: 100%; }
}

/* 响应式设计 */
@media screen and (max-width: 1400px) {
  .flood-chart {
    width: 280px;
    height: 180px;
    top: 20%;
  }
}

@media screen and (max-width: 1200px) {
  .flood-chart {
    width: 250px;
    height: 160px;
    top: 25%;
    right: 1%;
  }
}
</style>